/*
 * Read file in COO format. File consists of a header
 * NZR
 * Array of nnz count for each nzr
 * COO sorted sorted by row number
 *
 *
 *
 * */
#include <stdlib.h>
#include <stdio.h>
#include "mpi.h"
#include <string.h>
#include "mpi_helper.h"
#include "fileparser.cpp"

int main(int argc, char* argv[]) {
	int np, myid;
	int bufsize, count;
	int rc;
	MPI_File myfile; /* Shared file */
	MPI_Status status; /* Status returned from read */

	/* Initialize MPI */
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &myid);
	MPI_Comm_size(MPI_COMM_WORLD, &np);
/*	char * filename = (char*) malloc(strlen("coo_mat.bin"));
	strcpy(filename, "coo_mat.bin");*/

	MPI_Datatype entry_type;
	COO_ITEM_TYPE(&entry_type);
	/* Open the file */
	rc = MPI_File_open(MPI_COMM_WORLD, "coo_mat.bin", MPI_MODE_RDONLY, MPI_INFO_NULL,&myfile);

	if (rc) {
		printf("Unable to open file \"temp\"\n");
		fflush(stdout);
	} else {
		int base = 0;
		int * nzr = (int*) malloc(sizeof(int));
		MPI_File_read_at(myfile, 0, nzr, 1, MPI_INT, &status);
		MPI_Offset offset = sizeof(int);

		int *row_counts = (int*) malloc(nzr[0] * sizeof(int));
		//MPI_File_seek(myfile, offset, MPI_SEEK_SET);
		printf("NNZ ROWS %d\n", nzr[0]);
		MPI_File_read(myfile, row_counts, nzr[0], MPI_INT, &status);
		MPI_Offset header_disp;
		MPI_File_get_position(myfile, &header_disp);
		printf("Offset=%d\n", header_disp);
		int row_offsets[nzr[0]];
		fill_n(row_offsets, nzr[0], 0);
		for (int i =1; i < nzr[0]; i++) {
			row_offsets[i] = row_offsets[i-1] + row_counts[i-1];
			printf("row_offset[i]=%d\n", row_offsets[i]);
		}

		// Assume p < nzr

		// Find the position in file to read
		int i = myid;
		COO_item * entries;
		while(row_offsets[i] != -1) {
			offset = header_disp	 + (row_offsets[i] * sizeof(COO_item));
			//MPI_File_set_view(myfile, offset, entry_type, entry_type, "native", MPI_INFO_NULL);
			MPI_Alloc_mem(sizeof(COO_item) * row_counts[i], MPI_INFO_NULL, &entries);
			//entries = (ABC_type*)malloc(sizeof(ABC_type) * row_counts[i]);
			MPI_File_seek(myfile, offset, MPI_SEEK_SET);
			MPI_File_read(myfile, entries, row_counts[i], entry_type, &status);

			MPI_Get_count(&status, entry_type, &count);
			printf("read %d entries\n", count);
			printf("i %d, row_offsets[i]=%d\n", i, row_offsets[i]);
			row_offsets[i] = -1;
			i = (i+1) % nzr[0];
			//delete entries;
			MPI_Free_mem(entries);

		}
		MPI_Free_mem(nzr);
		MPI_Free_mem(row_counts);
		MPI_File_close(&myfile);

	}
	MPI_Type_free(&entry_type);
	/* Get the size of the file */
	MPI_Finalize();
	exit(0);
}
